package main

import (
	"net/http"

	"github.com/gin-gonic/gin"
)

type Login struct {
	User     string `form:"user" json:"user" xml:"user" binding:"required"`
	Password string `form:"password" json:"password" xml:"password" binding:"required"`
}

func main() {
	router := gin.Default()
	router.POST("/login-json", func(ctx *gin.Context) {
		var loginJson Login
		if err := ctx.ShouldBindBodyWithJSON(&loginJson); err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
		}
		if loginJson.User != "leo" || loginJson.Password != "123" {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "unauthorized",
			})
			return
		}
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"message": "login success",
		})
	})

	router.POST("/login-xml", func(ctx *gin.Context) {
		var loginXml Login
		if err := ctx.ShouldBindXML(&loginXml); err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}
		if loginXml.User != "leo" || loginXml.Password != "123" {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "unauthorized",
			})
			return
		}
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"message": "login success",
		})
	})

	router.POST("/login-form", func(ctx *gin.Context) {
		var loginForm Login
		if err := ctx.ShouldBind(&loginForm); err != nil {
			ctx.JSON(http.StatusBadRequest, gin.H{
				"error": err.Error(),
			})
			return
		}
		if loginForm.User != "leo" || loginForm.Password != "123" {
			ctx.JSON(http.StatusUnauthorized, gin.H{
				"code":    401,
				"message": "unauthorized",
			})
			return
		}
		ctx.JSON(http.StatusOK, gin.H{
			"code":    0,
			"message": "login success",
		})
	})
	router.Run()
}
